package com.ziq.zcamp.dialog.share

import android.graphics.Bitmap
import android.text.TextUtils
import com.ziq.base.extension.launchWithTryAsyncGlobal
import com.ziq.zcamp.api.request.common.MiniACodeParam
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.ServiceEntryPointManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.ZXingCodeUtils
import com.ziq.zcamp.util.bitmap.BitmapUtil
import dagger.hilt.android.EntryPointAccessors
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class ShareUtil {

    companion object{

        fun getSanCode(param: MiniACodeParam, qrCodeUrl:String = "", qrCodeWidth:Int = 250, qrCodeHeight:Int = 250,
                       onSuccess: ((minCodeUrl:String, bitmap: Bitmap) -> Unit)? = {url, bitmap -> },
                       onFail: ((e: Exception) -> Unit)? = {}){
            launchWithTryAsyncGlobal(whenTry = {

                val entryPoint = EntryPointAccessors.fromApplication(
                    GlobalContextManager.appContext!!,
                    ServiceEntryPointManager::class.java
                )
                val respond = entryPoint.commonService().miniACode(param).request()
                if(respond.data?.url?.isNotEmpty() == true){
                    ImageUtil.getBitmap(0, respond.data?.url?:"", 0, 0) { id, bitmap ->
                        if (bitmap != null){
                            onSuccess?.invoke(respond.data?.url?:"", bitmap)
                        } else {
                            onFail?.invoke(Exception(""))
                        }
                    }
                } else {
                    getQRCode(qrCodeUrl, qrCodeWidth, qrCodeHeight, onSuccess = {
                        onSuccess?.invoke("", it)
                    }, onFail = {
                        onFail?.invoke(it)
                    })
                }
            }, whenCatch = {
                onFail?.invoke(it)
            })
        }


        fun getQRCode(qrCodeUrl:String, width:Int = 250, height:Int = 250,
                                onSuccess: ((bitmap: Bitmap) -> Unit)? = {},
                                onFail: ((e: Exception) -> Unit)? = {}){
            if (TextUtils.isEmpty(qrCodeUrl)) {
                return
            }
            Observable.just(qrCodeUrl)
                .observeOn(Schedulers.computation())
                .map { ZXingCodeUtils.createQRCode(it, width, height) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ code ->

                    if (BitmapUtil.isBitmapAvailable(code)) {
                        onSuccess?.invoke(code!!)
                    } else {
                        onFail?.invoke(Exception("二维码生成失败"))
                    }
                }, {
                    onFail?.invoke(Exception("二维码生成失败"))
                })
        }
    }
}